package drds.plus.rule_engine.table_rule;


import drds.plus.common.lifecycle.AbstractLifecycle;
import drds.plus.common.lifecycle.Lifecycle;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 一组{@linkplain TableRule}的集合
 */
@Slf4j
public class TableRuleSet extends AbstractLifecycle implements Lifecycle {
    @Setter
    @Getter
    protected Map<String, TableRule> tableNameToTableRuleMap;
    @Setter
    @Getter
    protected Map<String, String> tableNameToDataNodeIdMap;
    @Setter
    @Getter
    protected String defaultDataNodeId;
    @Setter
    @Getter
    protected boolean lazyInit = false;


    public void init() {
        for (Map.Entry<String, TableRule> entry : tableNameToTableRuleMap.entrySet()) {
            if (!lazyInit) {
                entry.getValue().init();
            }
        }
    }


    public void setTableNameToTableRuleMap(Map<String, TableRule> tableNameToTableRuleMap) {
        this.tableNameToTableRuleMap = new HashMap<String, TableRule>(tableNameToTableRuleMap.size());
        for (Entry<String, TableRule> entry : tableNameToTableRuleMap.entrySet()) {
            this.tableNameToTableRuleMap.put(entry.getKey().toLowerCase(), entry.getValue()); // 转化大写
        }
    }

    public Map<String, TableRule> getTableNameToTableRuleMap() {
        for (Map.Entry<String, TableRule> entry : tableNameToTableRuleMap.entrySet()) {
            TableRule tableRule = entry.getValue();
            if (tableRule != null && lazyInit && !tableRule.isInited()) {
                tableRule.init();
            }
        }
        return tableNameToTableRuleMap;
    }

    public TableRule getTableRule(@NonNull String tableName) {
        TableRule tableRule = tableNameToTableRuleMap.get(tableName.toLowerCase());
        if (tableRule != null && lazyInit && !tableRule.isInited()) {
            tableRule.init();
        }
        return tableRule;
    }

    public Logger log() {
        return log;
    }
}
